<?php

namespace App\Http\Services\common;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;

class WxService
{

    public $miniProgramApp;

    // 订阅消息跳转地址
    public $subscribeUrl = 'pages/note/index?id=%s&info=1';


    public function __construct()
    {
        $this->miniProgramApp = Factory::miniProgram(config('wechat.mini_program.codingMaster'));
    }

    /**
     * @throws InvalidConfigException
     */
    public function getUserSession($code)
    {
        return $this->miniProgramApp->auth->session($code);
    }


    // 发送订阅消息一次性
    public function sendSubscribeMessage($openid, $data, $memosId, $templateId = '', $page = '')
    {
        if ($memosId) {
            $page = sprintf($this->subscribeUrl, $memosId);
        }

        if (empty($templateId)) {
            $templateId = config('wechat.mini_program.codingMaster.template_id');
        }

        return $this->miniProgramApp->subscribe_message->send([
            'touser' => $openid,
            'template_id' => $templateId,
            'page' => $page,
            'data' => $data,
            'miniprogram_state' => 'developer',
        ]);
    }
}
